package com.caolei1992.exception.handler;

import com.caolei1992.web.exception.UnauthorizedException;
import com.caolei1992.web.vo.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Administrator
 */
@Slf4j
@RestControllerAdvice
public class ExceptionController {

    /**
     * /**
     * 捕捉UnauthorizedException
     *
     * @return
     */
    @ExceptionHandler(UnauthorizedException.class)
    public AjaxResult handle401() {
        return AjaxResult.failWithStatus(401, "Unauthorized");
    }

    /**
     * 捕捉其他所有异常
     *
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult globalException(HttpServletRequest request, Throwable ex) {
        log.error("异常：", ex);
        if (log.isDebugEnabled()) {
            return AjaxResult.failWithStatus(getStatus(request).value(), ex.getMessage());
        } else {
            return AjaxResult.failWithStatus(getStatus(request).value(), "error");
        }
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}

